import * as React from 'react';
import './index.scss';
import type { IHelloWorldProps } from './IHelloWorldProps';
import { Modal } from 'antd';
import 'antd/dist/antd.css';
// import { useRef ,useEffect} from 'react';
const logo = require('../assets/LOGO.png') as string;
const NB = require('../assets/NB.png') as string;
interface Item {
  id: number;
  title: string;
  topTitle: string;
  period: string;
  startTime: string;
  endTime: string;
  activeTitle: string;
  bgColor: string;
  template: number;
  departments: { activeName: string; value: string }[];
  isHidden?: boolean; // 将isHidden设置为可选属性
}
export default class HelloWorld extends React.Component<IHelloWorldProps, { visible: boolean, list: Item[] }> {

  state = { visible: false, list: [] };

  handleCancel = (): void => {
    this.setState({
      visible: false,
    });
  };

  public render(): React.ReactElement<IHelloWorldProps> {
    function generateCalendar(year: any) {
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
        daysInMonth[1] = 29;
      }
      let startDate = new Date(year, 0, 1);
      while (startDate.getDay() !== 1) {
        startDate.setDate(startDate.getDate() - 1);
      }
      const calendar = [];
      let weekNumber = 1;
      for (let i = 0; i < 12; i++) {
        const month = months[i];
        const weekList = [];
        const endOfMonth = new Date(year, i + 1, 0);
        const currentDate = new Date(startDate.toString());
        while (currentDate <= endOfMonth) {
          const weekStart = `${currentDate.getMonth() + 1}/${currentDate.getDate()}/${currentDate.getFullYear()}`;
          const endDate = new Date(currentDate.toString());
          endDate.setDate(endDate.getDate() + 6);
          const weekEnd = `${endDate.getMonth() + 1}/${endDate.getDate()}/${endDate.getFullYear()}`;
          weekList.push({
            week: `w${weekNumber}`,
            weekStart,
            weekEnd
          });
          currentDate.setDate(currentDate.getDate() + 7);
          weekNumber++;
        }
        calendar.push({
          month,
          weekList
        });
        startDate = currentDate;

      }
      return calendar;

    }
    const currentYear = new Date().getFullYear();
    const generatedCalendar = generateCalendar(currentYear);
    const activelist = [

      {
        topTitle: "Brand Marketing - Chariotte",
        topTitleBg: '#bf0101',
        contentText: 'CNY',
        active: [
          {
            activeTitle: 'Common Moments',
            activeBgColor: '#000000',
            startTime: "2025/1/20",
            endTime: "2025/1/27",

            allDept: [{
              activeName: "Fashionista",
              bgColor: "#d5dce4",
            },
            {
              activeName: "Urban Elite",
              bgColor: "#f2f2f2",
            },
            {
              activeName: "Urban Savry",
              bgColor: "#acb9c9",
            },
            {
              activeName: "Active Youth",
              bgColor: "#c8dac0",
            },
            {
              activeName: "Career Rookie",
              bgColor: "#fdfffe",
            },
            {
              activeName: "Runnerista",
              bgColor: "#c20001",
            },

            ],
            activeList: [

              {
                id: 2,
                title: "Shanghai Women Half Marathon 3/9",
                startTime: "2025/2/17",
                endTime: "2025/3/9",
                bgColor: "#e2d2f0",
                imgUrl: NB,
                content: "Runnerista (Female), Urban Runner (Female)Shanghai: Cloud Nine, MixC, Gate M, TKLSHWM SMU. Hot Mango PackUltra Light",
                activeTitle: 'Common Moments',
                template: 2,
                departments: [
                  { activeName: "Fashionista", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Elite", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Savry", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Active Youth", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Career Rookie", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Runnerista", value: "xxxxxxxxxxxxxxxxx" },

                ],
                topTitle: "Brand Marketing - Chariotte",
                period: '2',
              },

              {
                id: 7,
                title: "Valentine's Day",
                startTime: "2025/12/20",
                endTime: "2025/12/30",
                topTitle: "Brand Marketing - Chariotte",
                period: '2',
                bgColor: "#e2d2f0",
                activeTitle: 'Common Moments',
                isHidden: true,
                imgUrl: NB,
                template: 2,
                departments: [
                  { activeName: "Fashionista", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Elite", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Savry", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Active Youth", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Career Rookie", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Runnerista", value: "xxxxxxxxxxxxxxxxx" },

                ],
              },
            ],
          },

        ]
      },
      {
        topTitle: "Brand Marketing",
        topTitleBg: '#bf0101',
        contentText: 'CNY',
        content: '',
        active: [
          {
            activeTitle: 'Lifestyle',
            activeBgColor: '#000000',
            startTime: "2025/1/20",
            endTime: "2025/1/27",

            allDept: [{
              activeName: "Event/Moment",
              bgColor: "#d5dce4",
            },
            {
              activeName: "Target Consumer",
              bgColor: "#f2f2f2",
            },
            {
              activeName: "Featured Moments",
              bgColor: "#acb9c9",
            },
            {
              activeName: "PD-FTW",
              bgColor: "#c8dac0",
            },
            {
              activeName: "PD-APP",
              bgColor: "#fdfffe",
            },
            {
              activeName: "arketing Support",
              bgColor: "#4473c5",
            },



            ],
            activeList: [


              {
                id: 9,
                title: "Valentine's Day",
                startTime: "2025/12/20",
                endTime: "2025/12/30",
                topTitle: "Brand Marketing",
                period: '2',
                bgColor: "#e2d2f0",
                activeTitle: 'Common Moments',
                imgUrl: NB,
                isHidden: true,
                content: '',
                template: 2,
                departments: [
                  { activeName: "Fashionista", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Elite", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Savry", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Active Youth", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Career Rookie", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Runnerista", value: "xxxxxxxxxxxxxxxxx" },

                ],
              },
            ],
          },

        ]
      },
      {
        topTitle: "Energy Marketing",
        topTitleBg: '#bf0101',
        contentText: 'CNY',
        active: [
          {
            activeTitle: 'Energy',
            activeBgColor: '#000000',
            startTime: "2025/1/20",
            endTime: "2025/1/27",

            allDept: [{
              activeName: "Project Name",
              bgColor: "#d9d9d9",
            },
            {
              activeName: "Order Qty",
              bgColor: "#d9d9d9",
            },
            {
              activeName: "Traget Consumer",
              bgColor: "#d9d9d9",
            },
            {
              activeName: "SKETING sUPPORT",
              bgColor: "#d9d9d9",
            },
            {
              activeName: "Key Campagin",
              bgColor: "#d9d9d9",
            },
            {
              activeName: "App",
              bgColor: "#d9d9d9",
            },
            {
              activeName: "FTW",
              bgColor: "#d9d9d9",
            },


            ],
            activeList: [
              {
                id: 1,
                title: "Craft for Her 匠造自由灵感(2/6-2/16)",
                imgUrl: NB,
                startTime: "2025/2/6",
                endTime: "2025/2/16",
                activeTitle: 'Common Moments',
                bgColor: "#d8dff2",
                template: 2,
                content: `Active Youth (F) Urban Savvy (F)
Women's Day
FTW: 740/471/1906/860
APP: Q1 Jacket Franchise`,
                departments: [
                  { activeName: "Project Name", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Order Qty", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Traget Consumer", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Key Campagin", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "App", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "FTW", value: "xxxxxxxxxxxxxxxxx" },

                ],
                topTitle: "Brand Marketing",
                period: '2',
              },

              {
                id: 9,
                title: "Valentine's Day",
                startTime: "2025/12/20",
                endTime: "2025/12/30",
                topTitle: "Brand Marketing",
                period: '2',
                bgColor: "#e2d2f0",
                activeTitle: 'Common Moments',
                isHidden: true,
                content: '',
                template: 2,
                departments: [
                  { activeName: "Fashionista", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Elite", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Savry", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Active Youth", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Career Rookie", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Runnerista", value: "xxxxxxxxxxxxxxxxx" },

                ],
              },
            ],
          },

        ]
      },
      {
        topTitle: "Retail Marketing",
        topTitleBg: '#bf0101',
        contentText: 'CNY',
        active: [
          {
            activeTitle: 'E-Commerce',
            activeBgColor: '#000000',
            startTime: "2025/1/20",
            endTime: "2025/1/27",

            allDept: [{
              activeName: "Pjoject Name",
              bgColor: "#d5dce4",
            },
            {
              activeName: "Order Qty",
              bgColor: "#f2f2f2",
            },
            {
              activeName: "Traget Consumer",
              bgColor: "#acb9c9",
            },
            {
              activeName: "SKETING sUPPORT",
              bgColor: "#c8dac0",
            },
            {
              activeName: "Key Campagin",
              bgColor: "#fdfffe",
            },
            {
              activeName: "App",
              bgColor: "#fdfffe",
            },
            {
              activeName: "FTW",
              bgColor: "#fdfffe",
            },
            {
              activeName: "Others",
              bgColor: "#fdfffe",
            },


            ],
            activeList: [

              {
                id: 9,
                title: "Valentine's Day",
                startTime: "2025/12/20",
                endTime: "2025/12/30",
                topTitle: "Brand Marketing",
                period: '2',
                bgColor: "#e2d2f0",
                content: "",
                activeTitle: 'Common Moments',
                isHidden: true,
                template: 2,
                departments: [
                  { activeName: "Fashionista", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Elite", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Urban Savry", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Active Youth", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Career Rookie", value: "xxxxxxxxxxxxxxxxx" },
                  { activeName: "Runnerista", value: "xxxxxxxxxxxxxxxxx" },

                ],
              },
            ],
          },

        ]
      },

    ]
    function parseDate(dateStr: string) {
      try {
        const [month, day, year] = dateStr.split("/");
        const timestamp = new Date(Number(year), Number(month) - 1, Number(day)).getTime();
        if (isNaN(timestamp)) {
          throw new Error(`无效的日期格式: ${dateStr}`);
        }
        return timestamp;
      } catch (error) {
        console.log("2", error)
      }
    }
    function hamdTime(str: string) {
      const parts = str.split('/');
      const newStr = `${parts[1]}/${parts[2]}/${parts[0]}`;
      return newStr
    }
    function findWeek(data: { month: string; weekList: { week: string; weekStart: string; weekEnd: string; }[]; }[], startTime: string, isCutNum = true) {
      try {
        const start = parseDate(hamdTime(startTime)) || 0
        for (const monthData of data) {
          for (const week of monthData.weekList) {
            const weekStart = parseDate(week.weekStart) || 0
            const weekEnd = parseDate(week.weekEnd) || 0
            if (start >= weekStart && start <= weekEnd) {
              const weekNumber = week.week.replace("w", "");
              let num = isCutNum ? -1 : 0
              return parseInt(weekNumber, 10) + num // 转换为数字
            }
          }
        }
        return null;
      } catch (error) {
        console.log("3", error)
      }
    }

    function handleSyncScroll(e: React.UIEvent<HTMLDivElement>) {
      try {
        const targetElement = e.target as HTMLDivElement;

        const scrollLeft = targetElement.scrollLeft;

        // 获取所有需要同步滚动的元素
        const allCalenders = document.querySelectorAll<HTMLDivElement>('.calender');
        const allContentRights = document.querySelectorAll<HTMLDivElement>('.conent-right');

        allCalenders.forEach((calender) => {
          if (calender !== targetElement) {
            calender.scrollLeft = scrollLeft;

          }
        });

        allContentRights.forEach((contentRight) => {
          if (contentRight !== targetElement) {
            contentRight.scrollLeft = scrollLeft;
          }
        });

      } catch (error) {
        console.log("5", error)
      }
    }


    return (
      <div className='home-page'>
        <div className='page-container'>
          <div className='calendar-current'>
            <img
              width={34}
              src={logo}
            />
            NBC 2025 Calendar</div>
          <div className='top-bar'>Q1</div>
          <div className='top-container'>
            <div className="home-time">
              <div className='left-container'>
                <div className="pd-lr-4" >NBC 2025 Calendar</div>
                <div className="pd-lr-4">Owner:Shicai</div>
                <div className="pd-lr-4">Ver1.</div>
                <div className="pd-lr-4">1/6/2025</div>
              </div>
              <div className='month-top'>
                <div className="pd-lr-4">Month</div>
                <div className="pd-lr-4">Week</div>
                <div className="pd-lr-4">Week Start</div>
                <div className="pd-lr-4">Week End</div>
              </div>
            </div>
            {/* 日历 */}
            {/*  ref={calenderRef} onScroll={handleSyncScroll} */}
            <div className="calender" onScroll={handleSyncScroll} >
              <div className="calender-container"  >
                {generatedCalendar.map((monthData, index) => (
                  <div key={index} className='calender-one'>
                    <div className='month'>{monthData.month}</div>
                    <div className='flex-row'>
                      {monthData.weekList.map((week, weekIndex) => (
                        <div className='week' key={weekIndex}>{week.week}</div>
                      ))}
                    </div>
                    <div className='flex-row'>
                      {monthData.weekList.map((week, weekIndex) => (
                        <div className='week-start' key={weekIndex}>{week.weekStart}</div>
                      ))}
                    </div>
                    <div className='flex-row'>
                      {monthData.weekList.map((week, weekIndex) => (
                        <div className='week-end' key={weekIndex}>{week.weekEnd}</div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
          {/* 中间 */}
          <div className='content-continer'>
            {activelist.map((item, index) => (
              <div key={index} className='content-one'>
                {/* 活动-line */}
                <div className='dept-line' style={{ backgroundColor: index % 2 === 0 ? "#ebebeb" : "#f4f4f4" }}>
                  <div className="dept-line-content" style={{ backgroundColor: "#530412" }}>  {item.topTitle}</div>
                </div>
                {/* 活动content */}
                {item.active.map((data, i) => (
                  <div key={i} className='flex-row'>
                    <div className='conent-left' >
                      <div className='left-container' style={{ backgroundColor: data.activeBgColor }}>

                        <div className='mg-lr-10'>   {data.activeTitle}</div>
                      </div>
                      <div className='right-container'>
                        {data.allDept.map((deptObj, deptIndex) => (
                          <div className='bar-one' key={deptIndex} style={{ backgroundColor: deptObj.bgColor }}>
                            <div className='mg-lr-10'> {deptObj.activeName}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                    <div className='conent-right'
                      style={{ backgroundColor: index % 2 === 0 ? "#ebebeb" : "#f4f4f4" }}
                      onScroll={handleSyncScroll}>
                      <div className="activity-container"  >
                        {data.activeList.map((activity, dataINdex) => {

                          // 找到所有参与部门的索引
                          const deptIndices = data.allDept
                          console.log("deptIndices", deptIndices)
                          // 向左偏移量
                          const leftOffset = findWeek(generatedCalendar, activity.startTime) || 0
                          const endOffset = findWeek(generatedCalendar, activity.endTime, false) || 0
                          const divWidth = endOffset - leftOffset === 0 ? 1 : endOffset - leftOffset
                          // 找到最小的索引（即最近的部门）

                          // 判断是否是最后一个元素
                          const isLast = dataINdex === data.activeList.length - 1;
                          return deptIndices.length === 1 ? (

                            <div
                              key={activity.id}
                              className='content-title'
                              onClick={() => this.setState({
                                visible: true,
                                list: [activity],
                              })}

                              style={{
                                left: `${leftOffset * 130}px`,
                                width: `${divWidth * 130}px`,
                                height: "20px",
                                backgroundColor: activity.bgColor,
                                opacity: isLast ? 0 : 1, // 如果是最后一个元素，则设置透明度为0
                              }}
                            >
                              <div className="activity-header"  >{activity.title}</div>

                            </div>
                          ) : (

                            <div
                              key={activity.id}
                              className='content-title'
                              onClick={() => this.setState({
                                visible: true,
                                list: [activity],
                              })}


                              style={{
                                left: `${leftOffset * 130}px`,
                                width: `${divWidth * 130}px`,
                                height: `${deptIndices.length * 20}px`,
                                backgroundColor: "#fff",
                                opacity: isLast ? 0 : 1, // 如果是最后一个元素，则设置透明度为0
                              }}

                            >
                              <div className="activity-header-2" style={{ backgroundColor: "#4473c5" }}   >{activity.title}</div>
                              <div className='right-contont' style={{ WebkitLineClamp: deptIndices.length - 1 }}>
                                {activity.content}
                                <div>
                                  <img
                                    width={34}
                                    src={NB}
                                  />
                                </div>
                              </div>

                            </div>
                          );
                        })}

                      </div>

                    </div>
                  </div>
                ))}

              </div>
            ))}
          </div>


          <Modal title="Content" footer={null} mask={false} onCancel={this.handleCancel} visible={this.state.visible}
          >
            {this.state.list.map((item: Item, index) => (
              <div className="panel" key={index}>
                <div className="info-section">
                  <div className="info-item">
                    <span className="icon-circle">🕒</span>
                    <span className="label">Week Start:</span>
                    <span className="value">{item.startTime}</span>
                  </div>
                  <div className="info-item">
                    <span className="icon-circle">🕒</span>
                    <span className="label">Week End:</span>
                    <span className="value">{item.endTime}</span>
                  </div>
                  <div className="info-item">
                    <span className="icon-clock">⏰</span>
                    <span className="label">Period:</span>
                    <span className="value">{item.period} days</span>
                  </div>
                  <div className="info-item">
                    <span className="icon-department">💼</span>
                    <span className="label">Department:</span>
                    <span className="value">{item.topTitle}</span>
                  </div>
                  <div className="info-item">
                    <span className="icon-event">📅</span>
                    <span className="label">Event:</span>
                    <span className="value">{item.activeTitle}</span>
                  </div>
                </div>

                <div className="details-section">

                  <ul className="details-list" >
                    {item.departments.map((data: { activeName: unknown; value: unknown; }, dataIndex: React.Key | null | undefined) => {
                      return (
                        <li key={dataIndex}><span className='detail-li'>{data.activeName}:</span> {data.value}</li>
                      )
                    })}

                  </ul>
                </div>
              </div>
            ))}
          </Modal>

        </div>

      </div >
    );
  }
}
